using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Data.Core.Plugins;
using Avalonia.Markup.Xaml;
using SimpleToDoList.Services;
using SimpleToDoList.ViewModels;
using SimpleToDoList.Views;
using System.Linq;

namespace SimpleToDoList;

public partial class App : Application
{
    private readonly MainViewModel _mainViewModel = new MainViewModel();

    public override void Initialize()
    {
        AvaloniaXamlLoader.Load(this);
    }

    public override void OnFrameworkInitializationCompleted()
    {
        if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
        {
            // Line below is needed to remove Avalonia data validation.
            // Without this line you will get duplicate validations from both Avalonia and CT
            BindingPlugins.DataValidators.RemoveAt(0);

            var loadViewModel = new LoadViewViewModel();
            var load = new LoadView { DataContext = loadViewModel };

            loadViewModel.ToMainAction = todoList =>
            {
                foreach (var item in todoList)
                {
                    _mainViewModel.TodoItems.Add(new ToDoItemViewModel(item));
                }

                desktop.MainWindow = new MainWindow { DataContext = _mainViewModel };
                desktop.MainWindow.Show();

                load.Close();
            };
            desktop.MainWindow = load;

            // 监听关闭事件
            desktop.ShutdownRequested += DesktopOnShutdownRequested;
        }

        base.OnFrameworkInitializationCompleted();
    }

    private bool _canClose; // This flag is used to check if window is allowed to close

    private async void DesktopOnShutdownRequested(object? sender, ShutdownRequestedEventArgs e)
    {
        e.Cancel = !_canClose; // 首次取消闭幕活动

        if (!_canClose)
        {
            // 为了保存项目，我们将它们映射到更适合I/O操作的ToDoItem模型
            var itemsToSave = _mainViewModel.TodoItems.Select(item => item.GetToDoItem()).ToList();
            await ToDoListFileService.SaveToFileAsync(itemsToSave);

            // Set _canClose to true and Close this Window again
            _canClose = true;
            if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
            {
                desktop.Shutdown();
            }
        }
    }
}